import React, {
  useState,
  useEffect,
  useRef,
  forwardRef,
  useImperativeHandle,
} from 'react'
import { Table } from 'antd'
/**
 * request :{
 *  xhr: '',
 *  params:{}
 * }
 * listKey: 指定取vo下面哪个字段作为表格list
 */
const ATable = forwardRef((props, ref) => {
  const {
    request,
    columns = [],
    bordered = true,
    listKey = '',
    initData = [],
  } = props
  const [data, setData] = useState()
  const [loading, setLoading] = useState(false)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const prevParamsRef = useRef(null)

  useEffect(() => {
    if (initData?.length > 0) {
      setData(initData)
      return
    }
    // 检测请求参数是否改变，如果改变则重置到第一页
    const currentParams = JSON.stringify(request?.params || {})
    if (
      prevParamsRef.current !== null &&
      prevParamsRef.current !== currentParams
    ) {
      // 参数改变了，重置分页到第一页
      setPagination((prev) => ({
        ...prev,
        current: 1,
      }))
    }
    prevParamsRef.current = currentParams
    getData()
  }, [request, pagination.current])

  const getData = async (page = pagination.current) => {
    const { xhr, params = {} } = request || {}
    setLoading(true)
    try {
      const res = await xhr({
        page: page,
        pageSize: pagination.pageSize,
        ...params,
      })
      if (res?.success) {
        if (!listKey) {
          // 自动获取第一个字段下的data
          const list = Object.values(res?.vo || {})?.[0]?.data || []
          setData(list)
          // 获取总数
          const total = Object.values(res?.vo || {})?.[0]?.recordCount || 0
          setPagination((prev) => ({
            ...prev,
            total,
          }))
        } else {
          setData(res?.vo?.[listKey]?.data || [])
          setPagination({
            ...pagination,
            total: res?.vo?.[listKey]?.recordCount || 0,
          })
        }
      }
    } catch (error) {
      console.log('获取列表数据失败' + error)
    } finally {
      setLoading(false)
    }
  }
  // 处理分页变化
  const handleTableChange = (newPagination) => {
    setPagination(newPagination) // 更新页数
  }

  useImperativeHandle(ref, () => ({
    tableRefresh() {
      getData()
    },
  }))
  return (
    <Table
      columns={columns}
      dataSource={data}
      bordered={bordered}
      loading={loading}
      pagination={{
        ...pagination,
        position: ['bottomCenter'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 条`,
      }}
      onChange={handleTableChange}
    />
  )
})

export default ATable
